﻿using Abp.Dependency;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace Abp.Net.Sms
{
    public class Zz253SmsSender : SmsSenderBase, ITransientDependency
    {
        public Zz253SmsSender(ISmsSenderConfiguration configuration) : base(configuration)
        {
        }

        protected override void SendSms(SmsMessage sms)
        {
            Do(sms);
        }

        protected override Task SendSmsAsync(SmsMessage sms)
        {
            return Task.Run(() =>
            {
                Do(sms);
            });
        }

        private void Do(SmsMessage sms)
        {
            string result = string.Empty;
            sms.FreeSignName = string.IsNullOrWhiteSpace(sms.FreeSignName) ? _configuration.GetDefaultFreeSignName() : sms.FreeSignName;
            sms.TemplateCode = string.IsNullOrWhiteSpace(sms.TemplateCode) ? _configuration.GetDefaultSmsTemplateCode() : sms.TemplateCode;
            string content = sms.FreeSignName + string.Format(sms.TemplateCode, sms.TemplateParams);
            //string content = sms.FreeSignName + HttpUtility.UrlEncode(string.Format(sms.TemplateCode, sms.TemplateParams));
            string postJsonTpl = "\"account\":\"{0}\",\"sign\":\"{1}\",\"mobile\":\"{2}\",\"text\":\"{3}\"";
            if (sms.SendTime.HasValue)
            {
                postJsonTpl += string.Format(",\"sendtime\":\"{0}\"", sms.SendTime.Value.ToString("yyyyMMddHHmm"));
            }
            string jsonBody = "{" + string.Format(postJsonTpl, _configuration.GetAppKey(), _configuration.GetAppSecret(), sms.To, content) + "}";

            HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(_configuration.GetServiceUrl());
            httpWebRequest.ContentType = "application/json";
            httpWebRequest.Method = "POST";

            //// Create NetworkCredential Object 
            //NetworkCredential admin_auth = new NetworkCredential("username", "password");

            //// Set your HTTP credentials in your request header
            //httpWebRequest.Credentials = admin_auth;

            //// callback for handling server certificates
            //ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };

            using (StreamWriter streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
            {
                streamWriter.Write(jsonBody);
                streamWriter.Flush();
                streamWriter.Close();
                HttpWebResponse httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
                using (StreamReader streamReader = new StreamReader(httpResponse.GetResponseStream()))
                {
                    result = streamReader.ReadToEnd();
                }
            }
            dynamic obj = JsonConvert.DeserializeObject<dynamic>(result);
            if (obj != null && obj.code > 0)
            {
                throw new Exception(string.Format("Sms send fail.time:{0},msgId:{1},code:{2},errorMsg:{3}",
                        obj.time, obj.msgId, obj.code, obj.errorMsg));
            }
        }
    }
}
